const Service = require('egg').Service
const schedule = require('node-schedule')

class TeacherService extends Service {
  async index(categoryId) {
    const { ctx, app } = this
    // 获取当前老师
    const curTeacher = await ctx.find('Teacher', {}, 'findAll')

    const tmp = []
    if (curTeacher.length > 0) {
      curTeacher.forEach(item => {
        tmp.push(item.dataValues)
      })
    }
    // 添加任务队列
    const taskId = await ctx.service.cache.task.addTask()
    // 获取当前类别
    const curCategory = await ctx.find('CourseCategory', { where: { categoryId }, attributes: ['categoryName'] })
    // 获取课程对应的老师
    const curCourse = await ctx.find('Course', { where: { categoryId }}, 'findAll')
    const teachers = new Set()
    if (curCourse.length > 0) {
      curCourse.forEach(item => {
        teachers.add(item.dataValues.teacherId)
      })
    }
    const teacherTmp = [...teachers]
    let num = 0
    const teacherUrl = `${app.config.moocDomain}/web/j/memberBean.getMocMemberPersonalDtoById.rpc?csrfKey=${app.config.moocCookie.NTESSTUDYSI}`
    const job = schedule.scheduleJob('*/3 * * * * *', async() => {
      if (teacherTmp.length <= 0) {
        console.log('数据爬取完毕')
        await ctx.service.cache.task.updateTaskData({
          taskId,
          num,
          finished: true,
          title: curCategory.dataValues.categoryName
        })
        await ctx.service.cache.index.addLog(categoryId, num, 4)
        job.cancel()
        return
      }
      const memberId = teacherTmp.pop()
      const res = await ctx.helper.curlPost(teacherUrl, {
        memberId
      })
      const data = res.data
      if (data.code === 0) {
        const teacherCount = await this.createTeacher(data.result, tmp)
        num += teacherCount
        await ctx.service.cache.task.updateTaskData({
          taskId,
          num,
          finished: false,
          title: curCategory.dataValues.categoryName
        })
      }
    })
    return { taskId, num }
  }

  async createTeacher(data, teachers) {
    const { memberId, realName, schoolId, schoolName, lectorTitle, largeFaceUrl, followedCount, description } = data
    const postData = []
    const dict = {
      teacherId: memberId,
      teacherName: realName,
      schoolId,
      schoolName,
      lectorTitle,
      largeFaceUrl,
      followedCount,
      description
    }
    const index = teachers.findIndex(teacher => teacher.teacherId === memberId)
    if (index !== -1) {
      if (teachers[index].followedCount !== followedCount) {
        dict.id = teachers[index].id
        postData.push(dict)
      }
    } else {
      postData.push(dict)
    }
    if (postData.length > 0) {
      const res = await this.ctx.bulkCreate('Teacher', postData, { updateOnDuplicate: ['followedCount'] })
      return res.length
    }
    return 0
  }
}

module.exports = TeacherService
